
const fs = require('fs');
const path = require('path');

/**
 * 规则服务器，按照 whistle 官方文档规范实现
 * 这个函数会被 whistle 调用，用于获取插件提供的规则
 * 
 * @param {Object} server - whistle 提供的 server 对象
 * @param {Object} options - whistle 提供的配置对象
 */
module.exports = (server, options) => {
  console.log('[NoHost] 初始化 Rules Server (实时同步模式)');
  
  try {
    // 注册请求处理函数
    server.on('request', (req, res) => {
      try {
        console.log('[NoHost] RulesServer 收到规则请求 - 实时获取最新状态');
        
        // 实时生成当前激活环境的规则
        const rules = generateActiveRules();
        
        console.log('[NoHost] 实时生成的规则:', rules);
        
        // 设置强制无缓存响应头
        res.setHeader('Content-Type', 'text/plain; charset=utf-8');
        res.setHeader('Cache-Control', 'no-cache, no-store, must-revalidate');
        res.setHeader('Pragma', 'no-cache');
        res.setHeader('Expires', '0');
        res.setHeader('X-NoHost-Timestamp', new Date().toISOString());
        
        // 返回规则文本 - whistle 会解析这些规则并应用
        res.end(rules);
        
      } catch (error) {
        console.error('[NoHost] RulesServer 错误:', error);
        res.statusCode = 500;
        res.end('# NoHost Rules Server Error\n');
      }
    });
  } catch (error) {
    console.error('[NoHost] RulesServer 初始化失败:', error);
  }
};

/**
 * 生成当前激活环境的所有规则
 */
function generateActiveRules() {
  const rules = [];

  // 添加规则头部注释
  rules.push('# NoHost Plugin Rules');
  rules.push('# Generated at: ' + new Date().toISOString());
  rules.push('');

  try {
    // 直接读取 project.json 文件
    const dataFilePath = path.join(__dirname, '../public/project.json');
    let data = { projects: [] };
    
    if (fs.existsSync(dataFilePath)) {
      try {
        const fileContent = fs.readFileSync(dataFilePath, 'utf8');
        data = JSON.parse(fileContent);
      } catch (error) {
        console.error('[NoHost] 读取 project.json 失败:', error);
      }
    }

    // 获取所有激活的环境
    const activeEnvironments = [];
    data.projects.forEach(project => {
      project.environments.forEach(env => {
        if (env.isActive) {
          activeEnvironments.push({
            projectId: project.id,
            projectName: project.name,
            envId: env.id,
            envName: env.name,
            envType: env.type,
            hosts: env.hosts,
            isActive: env.isActive
          });
        }
      });
    });

    console.log('[NoHost] 激活的环境:', activeEnvironments);

    if (activeEnvironments.length === 0) {
      rules.push('# No active environments');
      return rules.join('\n');
    }

    // 添加通用调试信息
    rules.push('# === NoHost Plugin Active Environments ===');
    rules.push(`# Total active environments: ${activeEnvironments.length}`);
    rules.push('');

    // 为每个激活的环境生成规则
    activeEnvironments.forEach(env => {
      rules.push('');
      rules.push(`# === Project: ${env.projectName} ===`);
      rules.push(`# Environment: ${env.envName} (${env.envType})`);
      rules.push(`# Project ID: ${env.projectId}`);
      rules.push(`# Environment ID: ${env.envId}`);
      rules.push(`# Activation time: ${new Date().toISOString()}`);
      rules.push('');

      if (env.hosts && env.hosts.length > 0) {
        rules.push('# Host rules:');
        env.hosts.forEach(hostConfig => {
          if (hostConfig && hostConfig.trim()) {
            const rule = parseHostConfig(hostConfig);
            if (rule) {
              rules.push(rule);
            }
          }
        });
      } else {
        rules.push(`# ${env.projectName} - ${env.envName}: No configuration`);
      }

      // 添加一个调试头，便于验证规则是否生效
      rules.push(`# Add debug header for ${env.projectName}`);
      rules.push(`* reqHeaders://x-nohost-active-env=${env.projectName}-${env.envName}`);
      rules.push('');
    });

  } catch (error) {
    console.error('[NoHost] 生成规则失败:', error);
    rules.push('# Error generating rules: ' + error.message);
  }

  return rules.join('\n');
}

/**
 * 解析host配置为whistle规则格式
 * 输入: "127.0.0.1:8181 dgvip360.drivergenius3.com"
 * 输出: "dgvip360.drivergenius3.com 127.0.0.1:8181"
 */
function parseHostConfig(hostConfig) {
  if (!hostConfig || typeof hostConfig !== 'string') {
    return '';
  }

  const parts = hostConfig.trim().split(/\s+/);
  if (parts.length >= 2) {
    const proxy = parts[0]; // 127.0.0.1:8181
    const domain = parts[1]; // dgvip360.drivergenius3.com
    return `${domain} ${proxy}`;
  }

  return '';
}


